﻿using ACC.Business;
using ACC.Interface;
using ACC.Data.Line;
using System.Data;
using System.Data.Common;
using ACC.Util.DB;
using System;
using ACC.Data;
using ACC.Data.Comm;
using ACC.BusinessUtil;

namespace Script
{
    public class ProcessConfigEx : ProcessConfig
    {

        //static void LoadStationStatusWordCfg(BomCfg bom, LineData line, StnCfg stnCfg)
        //{

        //    string[] sql = new string[] {
        //        TSQLHelper.GetSql("LineLoader_LoadStatusWordCfg"),
        //       TSQLHelper.GetSql("LineLoader_LoadStatusWordCfg1")
        //    };

        //    if (stnCfg.StnStatusWordCfg.ContainsKey(bom))
        //        stnCfg.StnStatusWordCfg[bom].Clear();

        //    Object[][] param = new object[][] { new Object[] { line.Line, stnCfg.OPCfg.OP, stnCfg.Name, bom.ProductFamily }, 
        //        new Object[] {line.Line, stnCfg.OPCfg.OP, stnCfg.Name, bom.PartNo } };

        //    for (int i = 0; i < sql.Length; i++)
        //    {
        //        DataTable dt = DataManager.DBHelper.Query(sql[i], param[i]);
        //        DictionaryEx<int, PartTypeStatusWordCfg> statuswordlist = null;
        //        if (dt.Rows.Count > 0)
        //        {
        //            statuswordlist = new DictionaryEx<int, PartTypeStatusWordCfg>();
        //            stnCfg.StnStatusWordCfg[bom] = statuswordlist;
        //        }
        //        foreach (DataRow row in dt.Rows)
        //        {
        //            PartTypeStatusWordCfg cfg = new PartTypeStatusWordCfg();
        //            cfg.RecID = int.Parse(row["REC_ID"].ToString());
        //            cfg.CTime = DateTime.Parse(row["CTIME"].ToString());
        //            cfg.Name = row["NAME"].ToString();
        //            cfg.Type = (StatusWordType)int.Parse(row["TYPE"].ToString());
        //            cfg.Description = row["DESCRIPTION"].ToString();
        //            cfg.PLCName = row["PLC_NAME"].ToString();
        //            cfg.PLCTagAddr = row["PLC_TAG_ADDR"].ToString();
        //            cfg.Status = row["STATUS"].ToString() != "0";

        //            statuswordlist[cfg.RecID] = cfg;
        //        }
        //    }
        //}

        protected override void OnDataUpdate(ProcessConfig.UpdateOprator uo, DbTransaction trans, string UserID, string tableName, DataRow oldrow, DataRow newrow)
        {
            base.OnDataUpdate(uo, trans, UserID, tableName, oldrow, newrow);

            DataRow row = newrow == null ? oldrow : newrow;
            if (row == null || !row.Table.Columns.Contains("LINE"))
                return;

            LineData line = LineManager.GetLineData(row["LINE"].ToString());
            if (null == line)
                return;

            #region 修改Stn statusword/failureword配置后无需重新启动线
            //if ("ACC_PARTTYPE_STATUSWORD_CFG".Equals(tableName))
            //{
            //    string cfgclass = row["CLASS"].ToString();
            //    string productfamily = row["PRODUCT_FAMILY"].ToString();

            //    if (cfgclass == "0")
            //    {
            //        try
            //        {
            //            LoadStationStatusWordCfg(line.RunningData.RunningPartNos[row["PartNo"].ToString()].BomCfg, line, line.Cfg.StnCfg[row["STN"].ToString()]);
            //        }
            //        catch
            //        { }
            //    }
            //    else
            //    {
            //        foreach (string runpn in line.RunningData.RunningPartNos.Keys)
            //        {
            //            if (productfamily == line.RunningData.RunningPartNos[runpn].BomCfg.ProductFamily)
            //            {
            //                try
            //                {
            //                    LoadStationStatusWordCfg(line.RunningData.RunningPartNos[runpn].BomCfg, line, line.Cfg.StnCfg[row["STN"].ToString()]);
            //                }
            //                catch
            //                { }
            //            }
            //        }
            //    }
            //}
            #endregion

            #region 修改Stn配置后无需重新启动线
            if ("ACC_LINE_STN_CFG".Equals(tableName))
            {
                if (oldrow == null)
                {
                    return;
                }
                line.Cfg.StnCfg[row["STN"].ToString()].OprLogon = row["OPRLOGON"].ToString() == "1";
                line.Cfg.StnCfg[row["STN"].ToString()].OprValidate = row["OPRVALIDATE"].ToString() == "1";
                line.Cfg.StnCfg[row["STN"].ToString()].OprLogonLimit = UInt32.Parse(row["OPRLOGON_LIMIT"].ToString() == "" ? "1" : row["OPRLOGON_LIMIT"].ToString());
                line.Cfg.StnCfg[row["STN"].ToString()].RepeatLimit = Int32.Parse(row["REPEAT_LIMIT"].ToString() == "" ? "0" : row["REPEAT_LIMIT"].ToString());
                line.Cfg.StnCfg[row["STN"].ToString()].ReworkLimit = UInt32.Parse(row["REWORK_LIMIT"].ToString() == "" ? "0" : row["REWORK_LIMIT"].ToString());
                line.Cfg.StnCfg[row["STN"].ToString()].WaitTimeLimit = UInt32.Parse(row["WAITTIME_LIMIT"].ToString() == "" ? "0" : row["WAITTIME_LIMIT"].ToString());
                line.Cfg.StnCfg[row["STN"].ToString()].AutoModelChg = row["AUTOMODELCHG"].ToString() == "1";
                line.Cfg.StnCfg[row["STN"].ToString()].LoadFailureLog = row["LOADFAILURELOG"].ToString() == "1";

                switch (row["LOTCHANGE"].ToString())
                {
                    case "0":
                        line.Cfg.StnCfg[row["STN"].ToString()].LotTrackType = StnLotTrackType.None;
                        break;
                    case "2":
                        line.Cfg.StnCfg[row["STN"].ToString()].LotTrackType = StnLotTrackType.LoadLotNo;
                        break;
                    default:
                        line.Cfg.StnCfg[row["STN"].ToString()].LotTrackType = StnLotTrackType.NomalTrack;
                        break;
                }

                switch (row["LIMIT_CHECK"].ToString())
                {
                    case "1":
                        line.Cfg.StnCfg[row["STN"].ToString()].LimitCheckType = LimitCheckType.WarningOnly;
                        break;
                    case "2":
                        line.Cfg.StnCfg[row["STN"].ToString()].LimitCheckType = LimitCheckType.ChangeToNOK;
                        break;
                    default:
                        line.Cfg.StnCfg[row["STN"].ToString()].LimitCheckType = LimitCheckType.NotCheck;
                        break;
                }
            }
            #endregion

            #region 修改ProcData配置后无需重新启动线
            if ("ACC_PROCDATA_CFG".Equals(tableName))
            {
                string cfgclass = row["CLASS"].ToString();
                string productfamily = row["PRODUCT_FAMILY"].ToString();

                if (cfgclass == "0")
                {
                    StationUtil.ReloadStationPLCProcessData(line.Cfg.StnCfg[row["STN"].ToString()], row["PartNo"].ToString(), trans);
                }
                else
                {
                    foreach (string runpn in line.RunningData.RunningPartNos.Keys)
                    {
                        if (productfamily == line.RunningData.RunningPartNos[runpn].BomCfg.ProductFamily)
                        {
                            StationUtil.ReloadStationPLCProcessData(line.Cfg.StnCfg[row["STN"].ToString()], runpn, trans);
                        }
                    }
                }
            }
            #endregion

            #region 修改PartTypeTag配置后无需重新启动线
            if ("ACC_PARTTYPE_TAG_CFG".Equals(tableName))
            {
                string cfgclass = row["CLASS"].ToString();
                string productfamily = row["PRODUCT_FAMILY"].ToString();

                if (cfgclass == "0")
                {
                    //LineLoader.LoadPartTypeTag(line.Cfg.BomCfg[row["PARTNO"].ToString()]);
                }
                else
                {
                    foreach (string runpn in line.RunningData.RunningPartNos.Keys)
                    {
                        if (productfamily == line.RunningData.RunningPartNos[runpn].BomCfg.ProductFamily)
                        {
                            //LineLoader.LoadPartTypeTag(line.Cfg.BomCfg[runpn]);
                        }
                    }
                }
            }
            #endregion

            #region 修改ReturnCode配置后无需重新启动线
            if ("ACC_RTN_CODE_CFG".Equals(tableName))
            {
                string acccodein = row["ACC_CODE_IN"].ToString();
                int nCodeIn = 0;
                if(!string.IsNullOrEmpty(acccodein))
                {
                    int.TryParse(acccodein, out nCodeIn);
                }
                if (nCodeIn > 0)
                {
                    if (!line.Cfg.RtnCodeCfg.ContainsKey(nCodeIn))
                    {
                        ReturnCodeCfg cfg = new ReturnCodeCfg();

                        cfg.DescIn = row["DESC_IN"].ToString();
                        cfg.ACCCodeOut = row["ACC_CODE_OUT"].ToString();
                        cfg.DescOut = row["DESC_OUT"].ToString();
                        cfg.Action = ReturnCodeActionType.Default;

                        if (row.Table.Columns.Contains("ACTION") && row["ACTION"].ToString() != "")
                        {
                            cfg.Action = Enum.IsDefined(typeof(ReturnCodeActionType), Convert.ToInt32(row["ACTION"]))
                              ? (ReturnCodeActionType)Convert.ToInt32(row["ACTION"])
                              : ReturnCodeActionType.Default;
                        }

                        line.Cfg.RtnCodeCfg[nCodeIn] = cfg;
                    }
                    else
                    {
                        line.Cfg.RtnCodeCfg[nCodeIn].DescIn = row["DESC_IN"].ToString();
                        line.Cfg.RtnCodeCfg[nCodeIn].ACCCodeOut = row["ACC_CODE_OUT"].ToString();
                        line.Cfg.RtnCodeCfg[nCodeIn].DescOut = row["DESC_OUT"].ToString();
                        line.Cfg.RtnCodeCfg[nCodeIn].Action = ReturnCodeActionType.Default;

                        if (row.Table.Columns.Contains("ACTION") && row["ACTION"].ToString() != "")
                        {
                            line.Cfg.RtnCodeCfg[nCodeIn].Action = Enum.IsDefined(typeof(ReturnCodeActionType), Convert.ToInt32(row["ACTION"]))
                              ? (ReturnCodeActionType)Convert.ToInt32(row["ACTION"])
                              : ReturnCodeActionType.Default;
                        }
                    }

                }
            }
            #endregion
        }

    }
}
